package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.mapper.DeptMapper;
import com.itheima.mapper.EmpExprMapper;
import com.itheima.mapper.EmpMapper;
import com.itheima.pojo.*;
import com.itheima.service.EmpService;
import com.itheima.utils.JwtUtils;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;

@Slf4j
@Service
@Scope("prototype")
//@Lazy
public class EmpServiceImpl extends ServiceImpl<EmpMapper , Emp> implements EmpService {
//    @Autowired
//    private EmpMapper empMapper;
//    @Override
//    public PageResult<Emp> selectEmp(Integer page, Integer pageSize) {
//        //访问持久层
//        Long total = empMapper.getTotal();
//        //起始索引
//        int index = (page - 1) * pageSize;
//        List<Emp> empList = empMapper.selectEmp(index , pageSize);
//        PageResult<Emp> pageResult = new PageResult<>();
//        pageResult.setTotal(total);
//        pageResult.setRows(empList);
//
//        return pageResult;
//    }


    @Autowired
    private EmpMapper empMapper;
    @Autowired
    private EmpExprMapper empExprMapper;
    @Autowired
    private DeptMapper deptMapper;

    @Override
    public PageResult<Emp> selectEmp(EmpQueryParam empQueryParam) {
        IPage<Emp> page = new Page<>(empQueryParam.getPage(), empQueryParam.getPageSize());
        //构建条件
        LambdaQueryWrapper<Emp> queryWrapper = new LambdaQueryWrapper<>();
        if (empQueryParam.getName() != null && !empQueryParam.getName().equals("")) {
            queryWrapper.like(Emp::getName, empQueryParam.getName());
        }
        if (empQueryParam.getGender() != null) {
            queryWrapper.eq(Emp::getGender, empQueryParam.getGender());
        }
        if (empQueryParam.getBegin() != null && empQueryParam.getEnd() != null) {
            queryWrapper.between(Emp::getEntryDate, empQueryParam.getBegin(), empQueryParam.getEnd());
        }

        //执行MP分页查询

        page = this.page(page, queryWrapper);
        page.getRecords().forEach(emp -> {
            Dept dept = deptMapper.selectById(emp.getDeptId());
            if (dept != null){
                emp.setDeptName(dept.getName());
            }
        });
        PageResult<Emp> pageResult = new PageResult<Emp>(page.getTotal(), page.getRecords());
        return pageResult;

    }

    /**
     * 新增员工
     *
     * @param emp
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveEmp(Emp emp) {
        //补全一些属性 创建时间 修改时间 密码
        emp.setCreateTime(LocalDateTime.now());
        emp.setUpdateTime(LocalDateTime.now());
        emp.setPassword("123456");

        //保存员工基本信息数据
        empMapper.insert(emp);

        //保存员工工作经历数据

        List<EmpExpr> exprList = emp.getExprList();
        if (!CollectionUtils.isEmpty(exprList)) {
            //给每个对象赋值员工id
            exprList.forEach((expr) -> {
                expr.setEmpId(emp.getId());
            });

            empExprMapper.saveBacth(exprList);
        }


    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void deleteEmp(List<Integer> ids) {
        //删除员工基本信息
        empMapper.deleteBatchIds(ids);
        //删除员工工作经历
        empExprMapper.deleteByEmpIds(ids);
    }

//    @Override
//    public Emp getEmpWithExprById(Integer id) {
//        return empMapper.getEmpWithEmpExprById(id);
//    }

    //编辑查看员工属性第二种方式
    @Override
    public Emp getEmpById(Integer id) {
        //执行两个SQL
        //查询员工基本信息
        LambdaQueryWrapper<Emp> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Emp::getId, id);
        Emp emp = empMapper.selectOne(queryWrapper);   //MP
        //查询此员工的工作经历
        List<EmpExpr> exprList = empExprMapper.selectByEmpId(id);

        emp.setExprList(exprList);
        return emp;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateEmp(Emp emp) {
        //更改员工的基本信息
/*        UpdateWrapper<Emp> updateWrapper = new UpdateWrapper<>();  //MP
        updateWrapper.eq("id",emp.getId());               //MP*/

        emp.setUpdateTime(LocalDateTime.now());
        empMapper.updateById(emp);                  //MP

        //删除此员工的工作经历
        Integer id = emp.getId();
        empExprMapper.deleteByEmpIds(Arrays.asList(id));
        //新增此员工的工作经历
        if (!CollectionUtils.isEmpty(emp.getExprList())) {
            emp.getExprList().forEach(empExpr -> empExpr.setEmpId(id));
            //调用新增工作经历方法
            empExprMapper.saveBacth(emp.getExprList());
        }
    }

    /**
     * 查询全部员工数据
     *
     * @return
     */
    @Override
    public List<Emp> selectAllEmp() {
        List<Emp> empList = empMapper.selectList(null); //MP
        return empList;
    }

    /**
     * 登录校验
     *
     * @param emp
     * @return
     */
    @Override
    public LoginInfo login(Emp emp) {
        LambdaQueryWrapper queryWrapper = new LambdaQueryWrapper<>();  //MP
        queryWrapper.eq(emp.getUsername(), emp.getPassword());
        Emp emp1 = empMapper.selectOne(queryWrapper);

//        Emp emp1 = empMapper.selectByUsernameAndPassword(emp.getUsername() , emp.getPassword());
        if (emp1 != null) {
            LoginInfo loginInfo = new LoginInfo();
            loginInfo.setId(emp1.getId());
            loginInfo.setUsername(emp1.getUsername());
            loginInfo.setName(emp1.getName());

            //使用JWT工具生成令牌token
            Map<String, Object> claims = new HashMap<>(); //这个map中不能方用户的敏感信息
            claims.put("id", emp1.getId());
            claims.put("username", emp1.getUsername());
            String token = JwtUtils.generateJwt(claims);
            loginInfo.setToken(token);
            return loginInfo;
        }
        return null;
    }


}
